package io.gitee.zicai.bus.adaptor;

import io.gitee.zicai.bus.bus.Bus;
import io.gitee.zicai.bus.bus.ISendBus;
import io.gitee.zicai.bus.core.IBusSender;
import io.gitee.zicai.bus.exception.BusAdaptorException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;

import javax.annotation.Resource;
import java.util.Map;

/**
 * BaseBusSendAdaptor
 *
 * @author zicai
 * @since 2021-01-19
 */
@Slf4j
public abstract class BaseBusSendAdaptor<S extends IBusSender, SB extends ISendBus<S, ST>, ST> implements IBusSendAdaptor<S, SB, ST> {

    @Resource
    protected ApplicationContext applicationContext;
    @Resource
    protected Bus bus;

    /**
     * 厂商的命令发送服务
     *
     * @param brandName 厂商名称
     * @return IBusSender
     */
    @Override
    public S getCmdSender(String brandName) {
        Map<String, IBusSender> senderMap = applicationContext.getBeansOfType(IBusSender.class);
        log.info(">>> IBusSender beanName -> {}", String.join(",", senderMap.keySet()));
        //noinspection unchecked
        return senderMap.entrySet().stream()
                .filter(entry -> entry.getKey().contains(brandName))
                .findFirst()
                .map(Map.Entry::getValue)
                .map(s -> (S) s)
                .orElseThrow(BusAdaptorException.ofSupplier("未找到厂商的命令发送服务"));
    }
}
